package application.view
{
	import application.ApplicationFacade;
	import application.model.ConfigProxy;
	import application.model.GatewayProxy;
	import application.view.components.Paging;
	
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	
	import org.puremvc.interfaces.IMediator;
	import org.puremvc.interfaces.INotification;
	import org.puremvc.patterns.mediator.Mediator;
	
	public class PagingMediator extends Mediator implements IMediator
	{
		public static const NAME:String = "PagingMediator";
		
		private var gateway:GatewayProxy;
		private var config:ConfigProxy;
		
		public function PagingMediator( viewComponent:Object )
		{
			super( viewComponent );
			
			gateway = facade.retrieveProxy( GatewayProxy.NAME ) as GatewayProxy;
			config = facade.retrieveProxy( ConfigProxy.NAME ) as ConfigProxy;
			
			paging.addEventListener(Paging.ITEM_CLICK, onItemClick);
		}
		
		override public function getMediatorName():String
		{
			return NAME;
		}
		
		override public function listNotificationInterests():Array
		{
			return new Array( ApplicationFacade.VIEW_INIT,
							  ApplicationFacade.MODEL_CHANGED );
		}
		
		override public function handleNotification(notification:INotification):void
		{
			switch ( notification.getName() )
			{
				case ApplicationFacade.VIEW_INIT:
					setPaging();
					break;
				
				case ApplicationFacade.MODEL_CHANGED:
					setPaging();
					break;
			}
		}
		
		protected function get paging():Paging
		{
			return viewComponent as Paging;
		}
		
		private function setPaging():void
		{
			var posts:ArrayCollection = gateway.posts;
			var total:Number = posts.length;
			var postsPerPage:Number = config.getData().postsPerPage;
			
			// Get number of pages.
			var numPages:Number = Math.ceil(total / postsPerPage);
			if ( numPages == 0 ) numPages = 1;
			
			// Clear the pages array befour adding new values.
			paging.pages = new Array();
			
			for ( var i:Number = 1; i < numPages+1; i++ )
			{
				paging.pages.push(i);
			}
			
			paging.startIndex = 0;
			paging.toDisplay = config.getData().pagesToDisplay;
			paging.selectedPage = 1;
			paging.render();
		}
		
		private function onItemClick(event:Event):void
		{
			var selectedPage:Number = paging.selectedPage;
			sendNotification( ApplicationFacade.PAGE_SELECTED, selectedPage );
		}
	}
}